<?php

namespace App\Http\Controllers;

//use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\UsersReg;
use App\Models\Book;
use App\Models\BookTempstorage;
use App\Models\Category as cat;
use App\Models\Tag;
use App\Models\BooksTag;
use Request;
use Auth;
use Mail;

class AdminBookTempstorageController extends Controller
{

    public function index()
    {
        //每页显示15个记录
        $pre_page = 15;
        //$posts = Book::paginate($pre_page);

        //获得所有会员添加的图书信息 按倒序
        $books = BookTempstorage::orderBy('book_id', 'desc')->paginate($pre_page);
        foreach ($books as $book) {
            //得到会员资料
            $book['users'] = $book->hasOneUsersReg;
        }
        return view('admin.userabooklist', array(
            'books' => $books
            ));
    }

    public function show($id)
    {
        // 显示会员添加的书籍的信息
        $books = BookTempstorage::find($id); 
        if($books == null) {
            // 如果书籍信息为空，跳到404页面
            abort(404);
        }
        return view('admin.ubookinfo', array(
            'books' => $books
            ));
    }

    public function edit($id)
    {
        // 编辑审核临时书籍的信息
        $tempbooks = BookTempstorage::find($id);
        if($tempbooks == null)
        {
            return '需要编辑审核的图书不存在！';
        }
        // 图书分类名字
        $cats  = cat::all();
        // 得到本图书的分类名字
        $catname = cat::find($tempbooks->cat_id);

        // 图书的标签
        $tags = Tag::all();        

        return view('admin.tempinfoedit', array('tempbooks' => $tempbooks, 'cats' => $cats, 'catname' => $catname, 'tags' => $tags));
    }

    public function store(Request $request, $id)
    {
        
        //把临时图书保存在到books数据库
         $books = new Book;
         $tempbooks = BookTempstorage::find($id);

         //判断有没有上传文件,  如果有上传文件，使用上传的文件，否则用临时文件
        if($request::hasFile('fengmian'))
        {
            //取得上传文件
            $file = $request::file('fengmian');
            //得到上传文件的扩展名
            $entension = $file -> getClientOriginalExtension();
            $dirName = "uploads/yds2/"; // linux 系统下的目录结构
            $filename = time(); //用时间作为文件名字
            // $newName = 'yds' . $filename . '.' . $entension;
            // $path = $file -> move($dirName, $newName);

            //获得图片文件的宽度，高度，文件类型 
            list($bigWidth, $bigHeight, $bigType) = getimagesize($file);
            /* 
            $bigType: 
            1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，
            7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，
            9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，
            15 = WBMP，16 = XBM 
            */        

            if($bigWidth > 300)
            {
                $width = 300;
                $height = $bigHeight * ($width  / $bigWidth);

                // 把文件读入一个字符串
                $imagedata = file_get_contents($file);
                // 创建缩略图画板
                $block = imagecreatetruecolor($width, $height);
                // 启用混色模式
                imagealphablending($block, false);
                // 保存PNG alpha通道信息
                imagesavealpha($block, true);
                // 创建原图画板
                $bigImg = imagecreatefromstring($imagedata);
                // 缩放
                imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHeight);

                // 小图片文件名字
                $newName = 'yds' . $filename . '.' . $entension;
                // 生成临时文件名,保存到$dirName目录下,此时文件数据为空
                $tmpFilename = tempnam($dirName, 'tmp');
                // 改变文件属性
                // chmod($tmpFilename, 0644);
                // 保存图片,写数据到临时文件里
                switch ($bigType) {
                    case 1: 
                        imagegif($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 2: 
                        // 保存临时文件，写数据到临时文件里
                        imagejpeg($block, $tmpFilename);
                        // 给临时文件$tmpFilename改名为$newName，并且保存到$dirName目录下
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 3: 
                        imagepng($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
                }
                // 销毁
                imagedestroy($block);

                //图片裁剪保存完毕end

                // 保存原始图片
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path_m = $file -> move($dirName, $newName_m);
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

            }
            else {
                // 图片宽度<=300
                $newName = 'yds' . $filename . '.' . $entension;
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path = $file -> move($dirName, $newName);
                $path_m = copy($path, $dirName . $newName_m);
                $path_m = $dirName . $newName_m;
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符
            }

            $books->bimg = $path;
            $books->bimg_m = $path_m;

            $tempfile = $tempbooks -> bimg;  //临时小图片
            if(file_exists($tempfile)){
                unlink($tempfile); //然后删除临时文件
            }
            $tempfile_m = $tempbooks -> bimg_m;  //临时大图片
            if(file_exists($tempfile_m)){
                unlink($tempfile_m); //然后删除临时文件
            }

            // $books->bimg = $path;
        }
        else {

        //$dirName = 'uploads\yds1\\'; //windows 系统下目录结构
        $tempfile = $tempbooks -> bimg;  //临时小图片
        $tempfile_m = $tempbooks -> bimg_m;  //临时大图片

        $newfile = str_replace("uploads/books_temp", "uploads/yds2", $tempfile); // 新图片,文件名字和临时图片文件名字一样
        $newfile_m = str_replace("uploads/books_temp", "uploads/yds2", $tempfile_m); // 新图片,文件名字和临时图片文件名字一样

        if(file_exists($tempfile)){
            copy($tempfile, $newfile);  //移动临时文件到新的目录        
            unlink($tempfile); //然后删除临时文件
        }

        if(file_exists($tempfile_m)){
            copy($tempfile_m, $newfile_m);  //移动临时文件到新的目录        
            unlink($tempfile_m); //然后删除临时文件
        }

        //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

        $books->bimg = $newfile;
        $books->bimg_m = $newfile_m;
        }

        $books->book_name = trim(request::input('bookname'));
        $books->yuanzuoming = trim(request::input('yuanzuoming'));
        $books->fubiaoti = trim(request::input('fubiaoti'));
        $books->zuozhe = trim(request::input('zuozhe'));
        $books->yizhe = trim(request::input('yizhe'));
        $books->chubanshe = trim(request::input('chubanshe'));
        $books->chubannian = trim(request::input('chubannian'));
        $books->yeshu = trim(request::input('yeshu'));
        $books->zhuangzhen = trim(request::input('zhuangzhen'));
        $books->dingjia = trim(request::input('dingjia'));
        $books->isbn = trim(request::input('isbn'));
        $books->congshu = trim(request::input('congshu'));
        $books->neirongjianjie = request::input('neirongjianjie');
        $books->zuozhejianjie = request::input('zuozhejianjie');
        $books->mulu = request::input('mulu');
        $books->cat_id = request::input('catname');
        $books->uid = $tempbooks -> uid; //添加图书的会员的uid
        $books->add_time = $tempbooks -> add_time;
        $books->last_update = $tempbooks -> add_time;

        $books->save(); //通过审核(收录)        

        // 保存对应的标签信息
        //$bookstag = new BooksTag;
        //$bookstag->book_id =$books->book_id;
        //$bookstag->tag_id = request::input('tagsname');
        //$bookstag->save(); 

        //发送审核邮件 禁用了getmypid()函数，无法使用
        // $booksid = $books->book_id; //得到新加入的书籍的book_id
        // $username = UsersReg::find($tempbooks -> uid);
        // $booksname = $books->book_name;
        // $data = ['email'=>$username->email, 'name'=>$username->user_name, 'booksname'=>$booksname, 'booksid'=>$booksid];
        // $flag =Mail::send('emails.books_shenhe', $data, function($message) use($data)
        // {
        //     $message->to($data['email'], $data['name'])->subject('夜读书：您发布的《'. $data['booksname'] .'》审核通过了！');
        // });
        // if($flag){
        //     return '审核通过；发送邮件成功！';
        // }else{
        //     return '审核通过，发送邮件失败！';
        // }
        //发邮件审核end

        $tempbooks->delete(); //同时删除通过审核的临时图书信息的数据

        return '审核通过！'; 

    }

    public function destroy($id)
    {
        
    if (Auth::check()) 
    {
        // 删除会员们添加的书籍信息
        $tempbooks = BookTempstorage::find($id);
        //获得要删除的文件名字
        $picName = $tempbooks->bimg;
        if(file_exists($picName))
            {
                //删除文件
                unlink($picName);
            }
        
        $tempbooks->delete();
        return $this->index();
    }

    }

}
